package com.seaboxdata.threadHandler;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author
 * @create 2021-05-25 17:20
 **/
@Component
@Slf4j
public class GpsRecordConnectHandler implements DisposableBean, Runnable {

    private Thread thread;

    @Value("${activemq.jfxt.url}")
    private String url;

    @Value("${activemq.jfxt.username}")
    private String username;

    @Value("${activemq.jfxt.password}")
    private String password;

    @Value("${activemq.jfxt.gpsRecord.queueName}")
    private String queueName;

    @Value("${interface.isTest}")
    private String isTest;

    @Autowired
    private GpsRecordHandler gpsRecordHandler;

    private boolean flag;

    @Autowired
    public void initThread() {
        if ("true".equals(isTest)) {
            return;
        }
        this.flag = true;
        this.thread = new Thread(this);
        thread.setName("gpsRecordConnectThread");
        this.thread.start();
        log.info("gpsRecord:gpsRecordConnectThread start");
    }


    @Override
    public void run() {
        ConnectionFactory factory;//连接实例

        Connection connection = null;//收发的线程实例

        Session session;//消息发送目标地址

        Destination destination;
        try {//实例化连接工厂

            factory = new ActiveMQConnectionFactory(username, password, url);//获取连接实例

            connection = factory.createConnection();//启动连接

            connection.start();//创建接收或发送的线程实例

            session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);//创建队列(返回一个消息目的地)

            destination = session.createQueue(queueName);

            MessageConsumer consumer = session.createConsumer(destination);//消息发布者添加监听器

            consumer.setMessageListener(gpsRecordHandler);

        } catch (JMSException e) {
            e.printStackTrace();
            log.error("gpsRecord:gpsRecordConnectThread error");
        }
    }

    @Override
    public void destroy() throws Exception {
        log.info("gpsRecord:gpsRecordConnectThread is down");
        this.flag = false;
    }
}
